<?php
/**
 * Created by PhpStorm.
 * Admininfo: Administrator
 * Date: 2017/12/12
 * Time: 12:06
 */
namespace app\common\controller;
use app\admin\model\Admingroup;
use app\admin\model\Area;
use app\admin\model\City;
use think\Config;
use think\Db;
class  Curt extends Baseadmin
{
	protected $table;
	protected $model;
	protected $fetchconfig;
	protected $upload;
	protected $uploadsconfig;
	protected $uploads;
	function __construct($upload=false,$uploadsConfig=['input_name'=>'coverFile', 'data_field'=>'cover' ])
	{
		parent::__construct();
		$controller = request()->controller();
		$this->table = hump2underline($controller);//获取当前控制器对应的表名
		$this->upload = $upload;
		$this->uploadsconfig = $uploadsConfig;
		$this->fetchconfig=[
			'add_success'=>url('showList'),
			'add_error'=>url(),
			'edit_success'=>url('showList'),
			'edit_error'=>url(),
			'del_success'=>url('showList'),
			'del_error'=>url()
		];
		$this->uploads=Config::get('UPLOADS');
		$this->initModel();
	}
	/**
	 * 初始化模型
	 */
	private function initModel(){
		$this->model = model($this->table);
	}
	/**
	 * 展示列表
	 */
	public function showList()
	{
	    $this->getall();
		return $this->fetch();
	}
	/**
	 * 新增界面
	 */
	public function showAdd()
	{
		return $this->fetch();
	}
	/**
	 * 添加数据公用
	 */
	public  function add(){
		$data=$this->request->param();
		$validate=validate($this->table);
		if(!$validate->check($data)){
			$this->error($validate->getError());
		 }
		if($this->upload){
			$file = request()->file($this->uploadsconfig['input_name']);
			if($file){
				// 移动到框架应用根目录/public/uploads/ 目录下
				$info = $file->validate(['size'=>$this->uploads['SIZE'],'ext'=>$this->uploads['EXT']])->move($this->uploads['PATH']);
				if($info){
					$data[$this->uploadsconfig['data_field']]= date("Ymd").'/'.$info->getFilename();
				}else{
					$this->error($file->getError());
				}
			}
	 	}
		$data=$this->adddatabefter($data);
		$res=$this->model->allowField(true)->save($data);
		$this->addend($res);
	}

	/*
	 * 处理数据
	 */
	public function adddatabefter($data){
		   return $data;
	}

	/*
	 * 商品数据初始化处理
	 */
	public function createData($data){
//	    $shopid = session('shopid');  后期取原始存储值
        $shopid = 2;
	    $data['goods_addtime'] = time();
        $data['shop_id'] = $shopid;
        $data['goods_unit'] = empty($data['goods_unit'])?'kg': $data['goods_unit'];
	    return $data;
    }
	public function addend($res){
		if($res){
			$this->success('添加成功',$this->fetchconfig['add_success']);
		}else{
			$this->error('添加失败',$this->fetchconfig['add_success']);
		}
	}
	/**
	 * 获取所有的数据
	 */
	public function getall(){
		$list = $this->model->where('status',1)->order('id desc')->paginate();
		$page = $list->render();
		$this->assign('list', $list);
		$this->assign('page', $page);
	}
    /**
     * 删除
     * @param string $id 要删除的id，多个以,分割
     */
    public function del($id)
    {
        $arr = explode(',', $id);
        $i = 0;
        foreach ($arr as $k => $v) {
            if (!$v) {
                continue;
            }
            $this->model->destroy($v,true);
            $i++;
        }
        $this->success('删除' . $i . '条数据', $this->fetchconfig['del_success']);
    }
    /**
     * 彻底删除
     * @param string $id 要删除的id，多个以,分割
     */
    public function deleted($id)
    {
        $arr = explode(',', $id);
        $i = 0;
        foreach ($arr as $k => $v) {
            if (!$v) {
                continue;
            }
            $this->model->destroy($v,true);
            $i++;
        }
        $this->success('彻底删除' . $i . '条数据', $this->fetchconfig['del_success']);
    }
    /**
     * @param $id
     * @return mixed
     */
    public function showEdit($id)
    {
        if (!$id) {
            $this->error('非法操作');
        }
        $select = $this->model->find($id);
        if (empty($select)) {
            $this->error('非法操作');
        }
        $select=$select->toArray();
        $this->assign('data', $select);

        return $this->fetch();
    }
    /**
     * 编辑
     * */
    public function edit()
    {
        $data=$this->request->param();
//      dump($data);
        $validate=validate($this->table);
        if(!$validate->scene('edit')->check($data)){
            $this->error($validate->getError());
        }
        $file = request()->file($this->uploadsconfig['input_name']);
        if($file){
            $info = $this->model->find($data['id']);
            $info =$info->toArray();
            if($info['cover']){
//                $url = $this->uploads['PATH'].'/'.$info['cover'];
//                unlink($url);
            }
            $info = $file->validate(['size'=>$this->uploads['SIZE'],'ext'=>$this->uploads['EXT']])->move($this->uploads['PATH']);
            if($info){
                $data[$this->uploadsconfig['data_field']]= date("Ymd").'/'.$info->getFilename();
            }else{
                $this->error($file->getError());
            }
        }
        $data = $this->editAfter($data);
        $info=$this->model->allowField(true)->isUpdate(true) ->save($data);
        if ($info) {
            $this->success('操作成功', $this->fetchconfig['edit_success']);
        } else {
            $this->success('未修改内容', $this->fetchconfig['edit_success']);
        }
    }
     /*
     * @param $data
     * @return mixed
     * 编辑数据处理
     */
    protected function editAfter($data)
    {
        return $data;
    }
    /*
     * @return array
     * 返回菜单的权限列表
     */
    protected function getmenulist(){
        $Usergroupmodel=new Admingroup();
        $list=$Usergroupmodel::all();
        $list=collection($list)->toArray();
        $this->assign('list',$list);
    }

    /**
     * @param $type
     * @param $id
     * @return \think\response\Json
     * 根据参数获取相应的市\县区
     */
    public function getcitylists($type,$id){
        if($type==1){
            $model=new City();
            $where['p_id']=$id;
        }else if ($type==2){
            $model=new Area();
            $where['c_id']=$id;
        }
        $where['status']=1;
        $list=$model->where($where)->select();
        return json($list);
    }
    /**
     *上传图片返回全路径以便编辑时候用到
     */
    public function uploadImg(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('images');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['size'=>$this->uploads['SIZE'],'ext'=>$this->uploads['EXT']])->move($this->uploads['PATH']);
        if($info){
            $info= date("Ymd").'/'.$info->getFilename();
            $img= Config::get('imgurl').$info;
            $data['url']=$img;;
        }else{
            $data['info']=$file->getError();
        }
        return json($data);
    }
    /**
     * @param $distance
     * @return mixed]
     *  距离
     * 根据距离来计算配送费用和时间
     */
    protected function dispatchingmoneytime($distance){
        $defaylt= Db::name('config')->where(['keys'=>'basics_default'])->value('value');
        $defaylt =explode('|',$defaylt);
        $more= Db::name('config')->where(['keys'=>'distance_more'])->value('value');
        $more =explode('|',$more);
        $three= Db::name('config')->where(['keys'=>'distance_three'])->value('value');
        $three =explode('|',$three);
        if($distance<=3){
              $money=$defaylt[0];
              $time=$defaylt[1];
        }
        if($distance>3 and $distance<=5 ){
            $money=($distance-3)*$three[0]+$defaylt[0];
            $time=($distance-3)*$three[1]+$defaylt[1];
        }
        if($distance>5){
            $money = ($distance-5)*$more[0]+2*$three[0]+$defaylt[0];
            $time = ($distance-5)*$more[1]+2*$three[1]+$defaylt[1];
        }
        $data['money ']=$money;
        $data['time']=$time;
        return $data;
    }

}